//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System.ComponentModel;
using System.IO;
using System.Workflow.ComponentModel;

namespace Microsoft.Research.ScientificWorkflow.Activities
{
    [Name("File Input To Memory Stream", "File Input")]
    [Description("Reads a local file and creates an I/O stream for that file")]
    [WorkflowCategory("Data")]
    public partial class FileInputStreamer : System.Workflow.ComponentModel.Activity
    {
        #region Property Definitions
        // Required Input Property
        public static DependencyProperty InputFileProperty =
            DependencyProperty.Register("InputFile", typeof(string), typeof(FileInputStreamer));
        // Output Property
        public static DependencyProperty OutputStreamProperty =
            DependencyProperty.Register("OutputStream", typeof(Stream), typeof(FileInputStreamer));

        [RequiredInputParam]
        [Name("Input File")]
        [Description("The location of the file to read (e.g. 'c:\\myfile.txt')")]
        public string InputFile
        {
            get { return ((string)(base.GetValue(FileInputStreamer.InputFileProperty))); }
            set { base.SetValue(FileInputStreamer.InputFileProperty, value); }
        }

        [OutputParam]
        [Name("Output Stream")]
        [Description("The file stream from which file contents can be read")]
        public Stream OutputStream
        {
            get { return ((Stream)(base.GetValue(FileInputStreamer.OutputStreamProperty))); }
        }
        #endregion

        public FileInputStreamer()
		{
			InitializeComponent();
		}

        /// <summary>
        /// Opens a stream on the input file 
        /// </summary>
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            if (!string.IsNullOrEmpty(InputFile))
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(InputFile);
                    FileStream stream = fileInfo.OpenRead();
                    base.SetValue(FileInputStreamer.OutputStreamProperty, stream);
                }
                catch (IOException)
                {
                    // Do nothing.
                }
            }

            return ActivityExecutionStatus.Closed;
        }
	}
}
